package com.prs.crm.flow;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.prs.crm.domain.flow.WorkFlowNode;
import com.prs.crm.domain.flow.WorkFlowTransition;
import com.prs.crm.exception.InValidException;

/**
 * 流程结点排序
 * @author prs.chenzhi
 *
 */
public class FlowSorter {
	
	private Collection<WorkFlowNode> nodes;
	
	private Collection<WorkFlowTransition> relations;

	private List<WorkFlowNode> nodeList;
	
	
	public FlowSorter(Collection<WorkFlowTransition> relations,
			Collection<WorkFlowNode> nodes)
	{
		this.relations = relations;
		this.nodes = new ArrayList<WorkFlowNode>();
		this.nodes.addAll(nodes);
		nodeList = new ArrayList<WorkFlowNode>();
	}
	
	public void sort()
	{
		Collection<WorkFlowTransition> transet = new ArrayList<WorkFlowTransition>();
		for (WorkFlowTransition trans: relations)
		{
			nodes.remove(trans.getEndnode());
		}
		if (nodes.size()==1)
		{
			boolean find = false;
			WorkFlowNode startNode = nodes.iterator().next();
			nodeList.add(startNode);
			while (startNode!=null)
			{
				find = false;
				for (WorkFlowTransition trans: relations)
				{
					if (trans.getStartnode().equals(startNode))
					{
						if (!transet.contains(trans))
						{
							startNode = trans.getEndnode();
							nodeList.add(startNode);
							find = true;
							transet.add(trans);
							break;
						}
					}
				}
				if (!find)
					startNode = null;
			}
		}
		else
		{
			throw new InValidException("结点关系设置不完全,请重设");
		}
		for (int i=0;i<nodeList.size();i++)
		{
			nodeList.get(i).setSequence(i);
		}
	}
	

	

	
	
}
